
//import de.l3s.boilerpipe.extractors.ArticleExtractor;
import beans.Logics;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
//import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
//import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.simple.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author Intel 1
 */
@WebServlet(name = "AspireWikifierAction", urlPatterns = {"/AspireWikifierAction.do"})
public class AspireWikifierAction extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    //private String Access-Control-Request-Method: POST;
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/plain;charset=UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject json_response = new JSONObject();
        String url = "";
        String text = "";

        String desc = "";
        Document doc = null;
        Elements elements = null;

        try {
            String word = request.getParameter("word").trim();
            System.out.println("Original Word = " + word);

            String splits[] = word.split(" ");
            String procesed_word = "";
            if (splits.length > 0) {
                for (String split : splits) {
                    procesed_word += split + "+";
                }
                procesed_word = procesed_word.substring(0,
                        procesed_word.length() - 1);
                word = procesed_word;
            }

            System.out.println("Processed Word = " + word);

            if (splits.length > 3 || splits.length <= 0) {
                json_response.put("status", "0");
                json_response.put("msg", "You have chosen no word or more than three words ! Please choose Three or less than three words !");
            } else if (splits.length == 1 && !Character.isUpperCase(splits[0].charAt(0))) {
                // if the entity is a single word with first character in lower case 
//                url += "http://en.wiktionary.org/wiki/" + word;
//                text = Logics.getTextFromUrl(url);
//                System.out.print("Text from Wiki Server : " + text);
//                
//                if (text != null) {
//                    doc = Jsoup.parse(text);
//                    elements = doc.select("#Noun");
//                    if (elements.size() > 0) {
//                        Element element = elements.get(0); // span
//                        System.out.println("Element Name :" + element.tagName());
//                        Element parent_element = element.parent(); // h3
//                        System.out.println("Element Name :"
//                                + parent_element.tagName());
//                        Element ol_element = parent_element.nextElementSibling()
//                                .nextElementSibling();
//                        System.out.println("Element Name :" + ol_element.tagName());
//                        text = ol_element.wrap("<ol></ol>").html();
//                        desc = text;
//                        json_response.put("status", "1");
//                        json_response.put("msg", desc);
//
//                    } else {
//                        desc = "Sorry We are not able to retrieve the information of the selected word. Try sarching new word.";
//                        json_response.put("status", "0");
//                        json_response.put("msg", desc);
//
//                    }
//
//                } else {
//                    desc = "Sorry We are not able to retrieve the information of the selected word. Try sarching new word.";
//                    json_response.put("status", "0");
//                    json_response.put("msg", desc);
//                }

                word += "+define";
                url += "http://www.google.com/search?q=" + word;
                text = Logics.getTextFromUrl(url);
                System.out.print("Text from Google Server : " + text);
                doc = Jsoup.parse(text);
                elements = doc.select("#ires");
                if (elements != null && elements.size() > 0) {
                    for (Element e : elements) {
//                        e.select(".lr_dct_ent_ph").remove();
//                        e.select(".lr_dct_sf_h").remove();
//                        e.select(".vk_gy").remove();

                        desc = e.select(".lr_dct_sf_sens").html();;
                    }
                    json_response.put("status", "1");
                    json_response.put("msg", desc);
                } else {
                    json_response.put("status", "0");
                    json_response.put("msg", "The chosen word is not an entity ! To find the meaning of a word please select one at a time and  not together! ");

                }

            } // if the entity is of two words
            else {
                if (Character.isUpperCase(splits[0].charAt(0))) {
                    word += "+Wiki";
                    url += "http://www.google.com/search?q=" + word;
                    text = Logics.getTextFromUrl(url);
                    System.out.print("Text from Google Server : " + text);
                    if (text != null && !text.equalsIgnoreCase("")) {
                        doc = Jsoup.parse(text);
                        elements = doc.select(".kno-rdesc");
                        if (elements != null && elements.size() > 0) {
                            for (Element e : elements) {
                                desc = e.text();
                            }
                            json_response.put("status", "1");
                            json_response.put("msg", desc);
                        } else {
                            Element ol_element = doc.select("#rso").first();
                            System.out.println("Ol Element=" + ol_element.tagName());
                            Element li_element = ol_element.select("li").first();
                            System.out.println("Li Element=" + li_element.tagName());
                            Element link_element = li_element.select(".f").first().select("._Fe").first();
                            if (link_element == null) {
                                link_element = li_element.select(".f").first().select("._jd").first();
                            }
                            if (link_element == null) {
                                link_element = li_element.select(".f").first().select("._md").first();
                            }
                             if (link_element == null) {
                                link_element = li_element.select(".f").first().select("._Tc").first();
                            }

                            if (link_element != null) {
                                System.out.println("URL Element=" + link_element.tagName());
                                url = "http://" + link_element.text();
                                System.out.println("URL =" + url);
                                if (url.contains("wikipedia")) {
                                    text = Logics.getTextFromUrl(url);
                                    doc = Jsoup.parse(text);
                                    Element first_para = doc.select("#mw-content-text").first().select("p").first();
                                    desc = first_para.text();
                                    json_response.put("status", "1");
                                    json_response.put("msg", desc);
                                } else {
                                    desc = "Sorry We are not able to retrieve the information of the selected word. Try sarching new word.";
                                    json_response.put("status", "0");
                                    json_response.put("msg", desc);
                                }
                            } else {
                                desc = "Sorry We are not able to retrieve the information of the selected word. Try sarching new word.";
                                json_response.put("status", "0");
                                json_response.put("msg", desc);
                            }

                        }
                    }

                } else {
                    json_response.put("status", "0");
                    json_response.put("msg", "The chosen word is not an entity ! To find the meaning of a word please select one at a time and  not together! ");
                }
            }

            System.out.println(json_response);
            out.println(json_response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
